import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_enjoy_plus/api/house.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/LoadingDialog.dart';

import 'package:flutter_enjoy_plus/utils/PromptAction.dart';
import 'package:flutter_enjoy_plus/utils/ShowPhotoDialog.dart';
import 'package:image_picker/image_picker.dart';

class HouseForm extends StatefulWidget {
  const HouseForm({super.key, required this.params});

  final Map<String, dynamic> params;

  @override
  State<HouseForm> createState() => _HouseFormState();
}

class _HouseFormState extends State<HouseForm> {
  String fileFrontName = ""; // 正面身份证名称
  String fileBackName = ""; // 反面身份证名称
  Map<String, dynamic> _formData = {
    'point': '', // 小区信息
    'building': '', // 小区楼栋信息
    'room': '', // 小区房间信息
    'room': '', // 业主姓名
    'gender': 1, // 业主性别0女1男
    'mobile': '', // 业主电话
    'idcardFrontUrl': '', // 身份证正面
    'idcardBackUrl': '', // 身份证背面
  };
//拉起相册
  _selectPhoto(String tag) async {
    ImagePicker picker = ImagePicker();
    XFile? file = await picker.pickImage(source: ImageSource.gallery);
    Navigator.pop(context);
    if (file != null) {
      _formData[tag] = file.path;
      setState(() {});
    }
  }

  Widget _buildAddIdcardPhoto(String tag, String info) {
    return GestureDetector(
      onTap: () {
        // 弹出层
        showBindSheet(context, () {
          _selectPhoto(tag);
        });
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const Icon(
            Icons.add,
            size: 30,
            color: Color.fromARGB(255, 85, 145, 175),
          ),
          Text(
            info,
            style: const TextStyle(
              color: Color.fromARGB(255, 85, 145, 175),
            ),
          ),
        ],
      ),
    );
  }

  Widget _getShowImage(String photoUrl) {
    if (kIsWeb || !photoUrl.startsWith('/data')) {
      return Image.network(photoUrl, fit: BoxFit.contain);
    } else {
      return Image.file(File(photoUrl), fit: BoxFit.contain);
    }
  }

  Widget _buildIdcardPhoto(String tag, String photoUrl) {
    return Stack(children: [
      SizedBox(
        width: MediaQuery.of(context).size.width - 20,
        height: 300,
        child: _getShowImage(photoUrl),
      ),
      Positioned(
        right: 0,
        top: 0,
        child: GestureDetector(
          child: const Icon(Icons.delete, color: Colors.red),
          onTap: () {
            setState(() {
              _formData[tag] = '';
            });
          },
        ),
      )
    ]);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // _formData["point"] = widget.params["point"];
    // _formData["building"] = widget.params["building"];
    // _formData["room"] = widget.params["room"];
    _formData = widget.params;
    _formData["name"] = widget.params["name"] ?? '';
    _formData["mobile"] = widget.params["mobile"] ?? '';
    _formData["idcardFrontUrl"] = widget.params["idcardFrontUrl"] ?? '';
    _formData["idcardBackUrl"] = widget.params["idcardBackUrl"] ?? '';
    _formData["gender"] = widget.params["gender"] ?? 1;

    _nameController.text = _formData['name'];
    _mobileController.text = _formData['mobile'];
    setState(() {});
  }

  TextEditingController _nameController = TextEditingController();
  TextEditingController _mobileController = TextEditingController();
  String getDisplayName() {
    return '${_formData["point"]}-${_formData["building"]}-${_formData["room"]}';
  }

  // 提交审核
  void _submit() async {
    if ((_formData["point"] as String).isEmpty ||
        (_formData["building"] as String).isEmpty ||
        (_formData["room"] as String).isEmpty) {
      PromptAction.showError("小区信息不能为空");
      return;
    }
    if ((_formData["name"] as String).isEmpty) {
      PromptAction.showError("业主姓名不能为空");
      return;
    }
    RegExp nameReg =
        RegExp(r'^[\u4e00-\u9fa5]{2,20}(·[\u4e00-\u9fa5]{2,20}){0,4}$');
    if (!nameReg.hasMatch(_formData["name"])) {
      PromptAction.showError("业主格式不正确");
      return;
    }
    if ((_formData["mobile"] as String).isEmpty) {
      PromptAction.showError("手机号不能为空");
      return;
    }
    RegExp phoneReg = RegExp(r'^1[3-9]\d{9}$');

    if (!phoneReg.hasMatch(_formData["mobile"])) {
      PromptAction.showError("手机号不符合标准格式");
      return;
    }
    if ((_formData["idcardFrontUrl"] as String).isEmpty ||
        (_formData["idcardBackUrl"] as String).isEmpty) {
      PromptAction.showError("身份证前后照片不能为空");
      return;
    }
    //弹窗
    showDialog(
        context: context,
        builder: (context) {
          return LoadingDialog(message: '数据提交中');
        });

    if ((_formData["idcardFrontUrl"] as String).startsWith('http') &&
        (_formData["idcardFrontUrl"] as String).startsWith('https')) {
      _formData["idcardFrontUrl"] =
          await _uploadImage(_formData['idcardFrontUrl'], 'front');
    }
    if ((_formData["idcardBackUrl"] as String).startsWith('http') &&
        (_formData["idcardBackUrl"] as String).startsWith('https')) {
      _formData["idcardBackUrl"] =
          await _uploadImage(_formData['idcardBackUrl'], 'front');
    }
    // print(_formData);
    try {
      _formData.remove('status');
      await submitAPI(_formData);
      Navigator.pop(context);
      PromptAction.showSuccess('添加成功');
      Navigator.popUntil(context, (route) {
        return route.settings.name == '/';
      });
    } catch (e) {
      PromptAction.showSuccess(e.toString());
    }
  }

  //上传图片
  _uploadImage(String url, String tag) async {
    FormData data = FormData.fromMap({
      'file': kIsWeb
          ? MultipartFile.fromBytes(await XFile(url).readAsBytes(),
              filename: tag == 'front' ? fileFrontName : fileBackName,
              contentType: DioMediaType("image", 'png'))
          : MultipartFile.fromFileSync(url)
    });

    var res = await uploadAPI(data);
    return res['url'];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_formData['id'] != null ? '编辑房屋信息' : '添加房屋信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.only(top: 10, bottom: 10),
        children: [
          // 房屋信息
          Container(
            padding: const EdgeInsets.all(10),
            child: const Text(
              '房屋信息',
              style: TextStyle(
                  color: Color.fromARGB(255, 97, 94, 94), fontSize: 16),
            ),
          ),
          Container(
            color: Colors.white,
            padding:
                const EdgeInsets.only(left: 10, right: 10, top: 15, bottom: 15),
            child: Text(getDisplayName()),
          ),
          // 业主信息
          Container(
            padding: const EdgeInsets.all(10),
            child: const Text(
              '业主信息',
              style: TextStyle(
                  color: Color.fromARGB(255, 97, 94, 94), fontSize: 16),
            ),
          ),
          // 业主姓名
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(left: 10, right: 10),
            child: TextField(
              maxLength: 15,
              controller: _nameController,
              decoration: const InputDecoration(
                labelText: '姓名',
                hintText: '请输入业主姓名',
                hintStyle: TextStyle(color: Colors.grey),
                border: InputBorder.none,
              ),
              inputFormatters: [
                LengthLimitingTextInputFormatter(10),
              ],
              onChanged: (String value) {
                // PromptAction.showInfo(value);
                _formData["name"] = _nameController.text; // UI变化更新数据的值
              },
            ),
          ),
          // 性别
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(left: 10, right: 10),
            child: Row(
              children: [
                const Text(
                  '性别',
                  style: TextStyle(fontSize: 16),
                ),
                const SizedBox(width: 20),
                Radio(
                  value: 1,
                  groupValue: _formData['gender'],
                  onChanged: (value) {
                    setState(() {
                      _formData['gender'] = value ?? '';
                    });
                  },
                ),
                const Text('男'),
                const SizedBox(width: 10),
                Radio(
                  value: 0,
                  groupValue: _formData['gender'],
                  onChanged: (value) {
                    setState(() {
                      _formData['gender'] = value ?? '';
                    });
                  },
                ),
                const Text('女'),
              ],
            ),
          ),
          // 业主手机号
          Container(
            color: Colors.white,
            padding: const EdgeInsets.only(left: 10, right: 10),
            child: TextField(
              keyboardType: TextInputType.phone,
              maxLength: 11,
              controller: _mobileController,
              decoration: const InputDecoration(
                labelText: '手机号',
                hintText: '请输入您的手机号',
                hintStyle: TextStyle(color: Colors.grey),
                border: InputBorder.none,
              ),
              inputFormatters: [
                LengthLimitingTextInputFormatter(11),
              ],
              onChanged: (String value) {
                _formData["mobile"] = value;
              },
            ),
          ),
          // 业主信息
          Container(
            padding: const EdgeInsets.all(10),
            child: const Text(
              '本人身份证照片',
              style: TextStyle(
                  color: Color.fromARGB(255, 97, 94, 94), fontSize: 16),
            ),
          ),
          Container(
            padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
            child: const Text(
              '请拍摄证件原件，并使照片中证件边缘完整，文字清晰，光线均匀。',
              style: TextStyle(
                  color: Color.fromARGB(255, 97, 94, 94), fontSize: 12),
            ),
          ),
          // 身份证正面
          Container(
            color: Colors.white,
            height: 320,
            padding: const EdgeInsets.all(10),
            child: _formData['idcardFrontUrl'] == ''
                ? _buildAddIdcardPhoto('idcardFrontUrl', '上传人像面照片')
                : _buildIdcardPhoto(
                    'idcardFrontUrl',
                    _formData['idcardFrontUrl'],
                  ),
          ),
          const SizedBox(height: 20),
          // 身份证反面
          Container(
            color: Colors.white,
            height: 320,
            padding: const EdgeInsets.all(10),
            child: _formData['idcardBackUrl'] == ''
                ? _buildAddIdcardPhoto('idcardBackUrl', '上传国徽面照片')
                : _buildIdcardPhoto(
                    'idcardBackUrl',
                    _formData['idcardBackUrl'],
                  ),
          ),
          const SizedBox(height: 20),
          // 提交审核
          Container(
            padding: const EdgeInsets.all(10),
            child: ElevatedButton(
              onPressed: () {
                // 提交审核
                _submit(); // 提交审核
              },
              child: const Column(
                children: [
                  SizedBox(height: 8),
                  Icon(Icons.exit_to_app),
                  Text('提交审核'),
                  SizedBox(height: 8)
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
